package site.jlopen.utils.jwt;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JwtTool {

	private static final Logger log = LoggerFactory.getLogger(JwtTool.class);

	//public final static String PAY_JWT_JSON_KEY = "json";
	public final static Integer PAY_JWT_EXPIRES_TIME = 30;
	public final static String JWTID = "carro";
	public final static String JWTSECRET = "@Qq66666jlopen";
	
	/**public static void main(String[] args) {
		String token = createToken(1L, "userName");
		System.out.println(token);
		System.out.println(key(token));
		System.out.println(verify(token));
	}**/
	
	public static String createToken(Long userId, String userName) {
		Date useDate = new Date();
		Calendar nowTime = Calendar.getInstance();
		nowTime.add(Calendar.DATE, PAY_JWT_EXPIRES_TIME);
		Date expiresDate = nowTime.getTime();
		//String jsonStr = BjWebJsonUtil.toJson(data);
		String token = JWT.create().withAudience(JWTID)
				//.withClaim(PAY_JWT_JSON_KEY, jsonStr)
				.withClaim("userId", userId)
				.withClaim("userName", userName)
				.withExpiresAt(expiresDate)
				.withIssuedAt(useDate)
                .sign(Algorithm.HMAC256(JWTSECRET));
		return token;
	}

	public static String key(String token) {
        try {
        	String key = JWT.decode(token).getAudience().get(0);
        	return key;
        } catch (JWTVerificationException e) {
        	log.error("获取token：{}的key异常，{}", token, e);
            return null;
        }
	}

	public static boolean verify(String token) {
        try {
        	JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JWTSECRET)).build();
        	jwtVerifier.verify(token);
        	return true;
        } catch (JWTVerificationException e) {
        	log.error("校验token：{}异常，{}", token, e);
            return false;
        }
	}

	public static Long getUserId(String token) {
        try {
        	JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JWTSECRET)).build();
        	DecodedJWT jWT = jwtVerifier.verify(token);
        	Map<String,Claim> jwtMap = jWT.getClaims();
        	return jwtMap.get("userId").asLong();
        } catch (JWTVerificationException e) {
        	log.error("校验token：{}异常，{}", token, e);
            return null;
        }
	}

	public static String getUserName(String token) {
        try {
        	JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JWTSECRET)).build();
        	DecodedJWT jWT = jwtVerifier.verify(token);
        	Map<String,Claim> jwtMap = jWT.getClaims();
        	return jwtMap.get("userName").asString();
        } catch (JWTVerificationException e) {
        	log.error("校验token：{}异常，{}", token, e);
            return null;
        }
	}

}
